package com.imstlife.vending.utils;

import android.content.Context;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.imstlife.vending.R;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import static java.lang.Integer.parseInt;

/**
 * 类描述：包含两个弹框   进入设置和数字弹框
 * 创建人：
 * 创建时间：
 */

public class DialogUtil {

    public DialogPassword dialogPassword;
    int codeType = 0;
    /**
     * 验证码算法
     *
     * @param strVerifyCode
     * @return
     */
    Object o = new Object();
    boolean net_nonet_flag;
    private AlertDialog dialog;
    private TextView psw_text;
    private String simpleTime;
    private long nowTime;// 当前时间

    //Dialog弹框
    public void administratorcheck(final Context context, final main_administratorcheck main_administratorcheck, final int flag, final String key, final boolean netZT) {
        //获取弹框是否在显示

        dialogPassword = new DialogPassword(context, flag);
        dialogPassword.setOkListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取存储的密码
                String judge = SharePersistentUtil.getSharePersistentString(context, key);
                //获取登录接口管理密码
                String adminpsw =SharePersistentUtil.getSharePersistentString(context, "adminPassword");
                if (judge.equals("") || judge == null) {
                    if (Cof.ADMINPWD.equals(dialogPassword.getInputVal()) || adminpsw.equals(dialogPassword.getInputVal())) {
                        try {
                            main_administratorcheck.ifcorrect();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        dialogPassword.cleanText();
                        dialogPassword.dismiss();
                    } else if (dialogPassword.getInputVal().equals("") || dialogPassword.getInputVal() == null) {
                        main_administratorcheck.ifnull();
                    } else {
                        main_administratorcheck.iferror();
                        dialogPassword.cleanText();
                    }
                } else {
                    if (judge.equals(dialogPassword.getInputVal()) || adminpsw.equals(dialogPassword.getInputVal())) {
                        try {
                            main_administratorcheck.ifcorrect();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        dialogPassword.cleanText();
                        dialogPassword.dismiss();
                    } else if (dialogPassword.getInputVal().equals("") || dialogPassword.getInputVal() == null) {
                        main_administratorcheck.ifnull();
                    } else {
                        main_administratorcheck.iferror();
                        dialogPassword.cleanText();
                    }
                }
            }
        });
        dialogPassword.show();

    }

    //因为Fragment不能使用自定义Dialog弹框，所以制作一个AlertDialog弹框
    public void plantdialog(final Context context, final more_plantdialog more_plantdialog, int flag, String phone_back) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(context);
        View view = View.inflate(context, R.layout.dialog_password_keyboard, null);
        psw_text = (TextView) view.findViewById(R.id.psw_checkout);
        psw_text.setText(phone_back);
        view.findViewById(R.id.one).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                psw_text.append("1");
            }
        });
        view.findViewById(R.id.two).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                psw_text.append("2");
            }
        });
        view.findViewById(R.id.three).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                psw_text.append("3");
            }
        });
        view.findViewById(R.id.four).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                psw_text.append("4");
            }
        });
        view.findViewById(R.id.five).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                psw_text.append("5");
            }
        });
        view.findViewById(R.id.six).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                psw_text.append("6");
            }
        });
        view.findViewById(R.id.seven).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                psw_text.append("7");
            }
        });
        view.findViewById(R.id.eight).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                psw_text.append("8");
            }
        });
        view.findViewById(R.id.nine).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                psw_text.append("9");
            }
        });
        view.findViewById(R.id.zero).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                psw_text.append("0");
            }
        });
        view.findViewById(R.id.delete).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String pswtext = pswText();
                if (!pswtext.equals("") && pswtext != null) {
                    String newpswtext = pswtext.substring(0, pswtext.length() - 1);
                    psw_text.setText(newpswtext);
                } else {
                    psw_text.setText("");
                }
                //closeplantdialog();
            }
        });
        view.findViewById(R.id.ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                closeplantdialog();
                more_plantdialog.ok_check(pswText());
                psw_text.setText("");
            }
        });
        if (flag == 0) {
            psw_text.setHint("请输入工厂模式密码");
        } else if (flag == 1) {
            psw_text.setHint("请输入当前密码");
        } else if (flag == 2) {
            psw_text.setHint("请输入新密码");
        } else if (flag == 3) {
            psw_text.setHint("请输入手机号");
        } else if (flag == 4) {
            psw_text.setHint("请设置开门时间");
        } else if (flag == 5) {
            psw_text.setHint("请输入验证码");
        }
        builder.setView(view);
        builder.setCancelable(true);
        dialog = builder.create();
        dialog.show();
        Window window = dialog.getWindow();
        window.setGravity(Gravity.CENTER);
        //window.setWindowAnimations(R.style.mystyle);
        WindowManager.LayoutParams params = window.getAttributes();
        params.width = WindowManager.LayoutParams.WRAP_CONTENT;
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(params);
    }

    //关闭AlertDialog弹框
    public void closeplantdialog() {
        dialog.dismiss();
    }

    //返回AlertDialog的TextView的数据方法
    public String pswText() {
        return psw_text.getText().toString().equals("") ? "" : psw_text.getText().toString();
    }

    private boolean judgeVerifyCode(Context context, String strVerifyCode, boolean net_ZT) {
        int codeLength = strVerifyCode.length();
        Log.i("tag", "输入验证码的长度:" + codeLength);
        if (codeLength != 6) {
            return false;
        }
        // 拆分
        String code1, code2, code4;
        code1 = strVerifyCode.substring(0, 2);
        code2 = strVerifyCode.substring(3, 6);
        // 第三位的校验数字
        code4 = strVerifyCode.substring(2, 3);
        // 异或验证第三位
        int parsecode1 = parseInt(code1);
        int parsecode2 = parseInt(code2);
        int num = (parsecode1 ^ parsecode2) % 10;
        int parsecode4 = parseInt(code4);

        if (num != parsecode4) {
            return false;
        }

        //        // 获取网络时间，如果没网络，则获取系统时间
        //        if (HttpUtil.isNetworkAvailable(context)&&net_ZT) {
        //            net_nonet_flag=true;
        //            new Thread() {
        //                @Override
        //                public void run() {
        //                    //synchronized (o){
        //                        try {
        //                            Log.e("LjwOpenyzm","请求");
        //                            URL url = new URL("http://www.baidu.com");
        //                            URLConnection uc = url.openConnection();
        //                            uc.connect();
        //                            long id = uc.getDate();
        //                            Date date = new Date(id);
        //                            SimpleDateFormat sdf = new SimpleDateFormat(
        //                                    "yyyyMMddHHmmss");
        //                            simpleTime = sdf.format(date);
        //                            try {
        //                                nowTime = sdf.parse(simpleTime).getTime();// 毫秒
        //                                Log.i("ttt", "获取到的网络时间:" + nowTime);
        //                            } catch (ParseException e) {
        //                                e.printStackTrace();
        //                            }
        //
        //                        } catch (MalformedURLException e) {
        //                            e.printStackTrace();
        //                        } catch (IOException e) {
        //                            e.printStackTrace();
        //                        }
        //                       // o.notify();
        //                        Log.e("LjwOpenyzm","notify");
        //                    //}
        //                }
        //            }.start();
        //        } else {
        net_nonet_flag = false;
        nowTime = System.currentTimeMillis();
        Log.i("ttt", "获取到的系统时间:" + nowTime);

        // 设置日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM", Locale.ENGLISH);
        // 获取当前时间、并转换为字符串
        String currentYear = sdf.format(new Date(System.currentTimeMillis()));
        Log.i("ttt", "获取到的系统年:" + currentYear);
        //获取保存的网络时间
        String time = SharePersistentUtil.getSharePersistentString(context, "time");
        Log.i("ttt", "获取到的系统年:" + time);
        if (time != null)
            if (!currentYear.equals(time)) {
                return true;
            }
        // }
        if (net_nonet_flag) {
            // 组合
            //synchronized (o){
            Log.e("LjwOpenyzm", "wait");
            try {
                //  o.wait();
            } catch (Exception e) {
                e.printStackTrace();
            }
            Log.e("LjwOpenyzm", "waitopen");
            Log.i("ttt", "获取到的网络时间2:" + nowTime);
            String code3 = code1 + code2;
            nowTime = nowTime / 1000;
            String currentTime = Long.toString(nowTime);
            if (currentTime.length() <= 5) {
                return false;
            }
            String subCurrentTime = currentTime.substring(0, 5);
            String checkCode = subCurrentTime + code3;
            Long checkCodeLong = Long.parseLong(checkCode);
            Log.i("checkCodeLong", "checkCodeLong：" + checkCodeLong);
            // 验证
            if (checkCodeLong >= nowTime - 1 * 60
                    && checkCodeLong <= nowTime + 1 * 60) {
                Log.e("==============", "潘大U呢");
                return true;
            } else {
                Log.e("=======2222=======", "潘大U呢");
                codeType = 1;
                return false;
            }
            //            /}
        } else {
            String code3 = code1 + code2;
            nowTime = nowTime / 1000;
            String currentTime = Long.toString(nowTime);
            if (currentTime.length() <= 5) {
                return false;
            }
            String subCurrentTime = currentTime.substring(0, 5);
            String checkCode = subCurrentTime + code3;
            Long checkCodeLong = Long.parseLong(checkCode);
            Log.i("checkCodeLong", "checkCodeLong：" + checkCodeLong);
            // 验证
            if (checkCodeLong >= nowTime - 1 * 60
                    && checkCodeLong <= nowTime + 1 * 60) {
                return true;
            } else {
                codeType = 1;
                return false;
            }
        }
    }

    //Dialog弹框接口
    public interface main_administratorcheck {
        void ifcorrect() throws IOException;

        void iferror();

        void ifnull();
    }

    //AlertDialog弹框接口
    public interface more_plantdialog {
        void ok_check(String str);
    }
}
